<template>
    <div class="manage">
        <h1>上下班打卡</h1>
        <div class="clock">
            {{ currentTime }}
        </div>
        <div class="clock">
            <button class="punch-button" @click="punchClock('上班卡')">
                上班打卡
            </button>
            <button class="punch-button" @click="punchClock('下班卡')" >
                下班打卡
            </button>
        </div>

        <div class="block_calendar">
            <el-calendar v-model="value">
                <template v-slot:dateCell="{ date }">
                    <div class="date-cell">
                        <span>{{ date.getDate() }}</span>
                        <p v-if="scheduleInfo[formatDate(date)] && scheduleInfo[formatDate(date)].isWorkday">
                            上班时间: {{ scheduleInfo[formatDate(date)].startTime }} - {{ scheduleInfo[formatDate(date)].endTime }}
                        </p>
                    </div>
                </template>
            </el-calendar>
        </div>
    </div>

</template>

<script>
import {addSign} from "@/api/Sign";
import {getUserSchedule} from "@/api/Schedule";

    export default {
        name: "Sign",
        data() {
            return {
                userId: '',
                value: new Date(),
                today: new Date(new Date()-new Date().getTimezoneOffset() * 60000).toISOString().replace("T", " ").split(".")[0],
                scheduleInfo: {}, // 存储每天的排班信息
                dateString:"",
                currentTime: "", // 当前时间
            };
        },
        created() {
            const user = JSON.parse(localStorage.getItem('user'));
            if (user) {
                this.userId = user.id;
            }
            this.fetchScheduleInfo();
            this.updateTime();
            setInterval(this.updateTime, 1000); // 每秒更新时间
        },
        methods: {
            async punchClock(punchType) {
                try {
                    const data = {
                        userId: this.userId,
                        date: this.today,
                        origin: '正常打卡',
                        punchType
                    };

                    // 等待后端接口响应
                    const response = await addSign(data);

                    // 如果后端返回成功
                    if (response && response.data && response.data.code === 200) {
                        this.$message.success(`${punchType}成功`);
                    } else {
                        // 如果后端返回失败
                        this.$message.error(response.data.message || "打卡失败");
                    }
                } catch (error) {
                    console.error("打卡失败:", error);
                    this.$message.error("打卡失败");
                }
            },
            async fetchScheduleInfo() {
                const startDate = new Date(this.value.getFullYear(), this.value.getMonth(), 1); // 当月第一天
                const endDate = new Date(this.value.getFullYear(), this.value.getMonth() + 1, 0); // 当月最后一天
                for (let date = new Date(startDate); date <= endDate; date.setDate(date.getDate() + 1)) {
                    const dateString = this.formatDate(date);
                    try {
                        const response = await getUserSchedule({ userId: this.userId, date: dateString });
                        const scheduleData = response.data// 确保 response.data 是一个对象
                        const formattedData = {
                            isWorkday: scheduleData.isWorkday,
                            startTime: this.formatTime(scheduleData.startTime),
                            endTime: this.formatTime(scheduleData.endTime)
                        };
                        this.$set(this.scheduleInfo, dateString, formattedData);

                    } catch (error) {
                        console.error("获取排班信息失败:", error);
                    }
                }
                this.$forceUpdate();
            },
            formatDate(date) {
                return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
            },
            formatTime(time) {
                if (!time) return "";
                const dateObj = new Date(time);
                return `${String(dateObj.getHours()).padStart(2, '0')}:${String(dateObj.getMinutes()).padStart(2, '0')}`;
            },
            updateTime() {
                const now = new Date();
                this.currentTime = `${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}:${String(now.getSeconds()).padStart(2, '0')}`;
            }
        }
    }
</script>

<style scoped>
    .manage {
        text-align: center;
        padding: 20px;
    }

    .punch-button {
        width: 150px;
        height: 50px;
        margin: 10px;
        border: none;
        border-radius: 25px;
        background-color: #4caf50;
        color: white;
        font-size: 16px;
        cursor: pointer;
        outline: none;
    }

    .punch-button:disabled {
        background-color: #ccc;
        cursor: not-allowed;
    }

    .punch-button:hover:not(:disabled) {
        background-color: #45a049;
    }
    .block_calendar{
        width: 100%;
        box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
        border-radius: 10px;
        margin: 10px;
    }
    .date-cell {
        text-align: center;
        min-height: 80px; /* 增加格子的最小高度 */
        padding: 5px; /* 添加内边距，使内容不紧贴边缘 */
        box-sizing: border-box; /* 确保内边距包含在格子高度内 */
        display: flex; /* 使用 Flexbox 布局 */
        flex-direction: column; /* 垂直排列子元素 */
        justify-content: center; /* 垂直居中对齐子元素 */
        align-items: center; /* 水平居中对齐子元素 */
    }
    .date-cell span {
        font-weight: bold; /* 使日期数字更突出 */
        margin-bottom: 2px; /* 添加一些间距 */
    }

    .date-cell p {
        margin: 2px 0; /* 调整段落之间的间距 */
        font-size: 12px; /* 调整字体大小 */
    }
    .clock {
        font-size: 24px;
        font-weight: bold;
        color: #333;
    }

</style>